<template>
  <div class="main" v-loading="loading">
    <!-- 标题的插槽 -->
    <div><slot></slot></div>
    <!-- 菜单区域 -->
    <div>
      <!-- 已经登录的情况 -->
      <div v-if="islogin">
        <!-- {{ userinfo.tbUser.username }} -->
        <el-dropdown @command="docommand">
          <div class="menu">
            <el-avatar :size="100" :src="userlogo" alt="" />
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </div>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>
                <el-icon><Lollipop /></el-icon>{{ userinfo.tbUser.username }}
              </el-dropdown-item>

              <el-dropdown-item divided command="home">
                <el-icon><HomeFilled /></el-icon>
                返回首页
              </el-dropdown-item>

              <el-dropdown-item divided command="logout">
                <el-icon><Cherry /></el-icon>退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!-- 没有登录的情况 -->
      <div v-if="!islogin">
        <el-button-group>
          <el-button @click="loginVisible = true" type="primary">登录</el-button>
          <el-button @click="regVisible = true" type="success">注册</el-button>
        </el-button-group>
      </div>
    </div>
  </div>

  <!-- 登录的对话框 -->
  <el-dialog v-model="loginVisible" title="用户登录">
    <div>
      <LoginComp @login-change="loginVisible = false"></LoginComp>
    </div>
  </el-dialog>

  <!-- 注册的对话框 -->
  <el-dialog v-model="regVisible" title="用户注册">
    <div>
      <RegComp @reg-success="reg">></RegComp>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { api } from '@/js/ajax'
import { storeToRefs } from 'pinia'
import { userstore } from '@/stores/userinfo'
import LoginComp from './LoginComp.vue'
import RegComp from './RegComp.vue'
import { useRouter } from 'vue-router'
const router = useRouter()

const { islogin, userinfo, userlogo } = storeToRefs(userstore())
const { updateUserInfo } = userstore()

const loading = ref(false)
const loginVisible = ref(false)
const regVisible = ref(false)

const reg = () => {
  regVisible.value = false
  loginVisible.value = true
}

const docommand = (command) => {
  if (command == 'logout') {
    logout()
  } else if (command == 'home') {
    router.push('/')
  }
}

const logout = () => {
  loading.value = true
  api.delete('/auth', {}, () => {
    updateUserInfo(() => {
      loading.value = false
    })
  })
}
</script>

<style scoped>
.main {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 1rem;
}
.menu {
  display: flex;
  align-items: center;
}
.menu img {
  width: 2rem;
  height: auto;
  display: block;
}
</style>

<style scoped></style>
